/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import controller.exceptions.IllegalOrphanException;
import controller.exceptions.NonexistentEntityException;
import controller.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import model.Creditos;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;
import model.Tipocredito;

/**
 *
 * @author AlexanderDiaz
 */
public class TipocreditoJpaController implements Serializable {

    public TipocreditoJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Tipocredito tipocredito) throws RollbackFailureException, Exception {
        if (tipocredito.getCreditosCollection() == null) {
            tipocredito.setCreditosCollection(new ArrayList<Creditos>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Collection<Creditos> attachedCreditosCollection = new ArrayList<Creditos>();
            for (Creditos creditosCollectionCreditosToAttach : tipocredito.getCreditosCollection()) {
                creditosCollectionCreditosToAttach = em.getReference(creditosCollectionCreditosToAttach.getClass(), creditosCollectionCreditosToAttach.getIdCredito());
                attachedCreditosCollection.add(creditosCollectionCreditosToAttach);
            }
            tipocredito.setCreditosCollection(attachedCreditosCollection);
            em.persist(tipocredito);
            for (Creditos creditosCollectionCreditos : tipocredito.getCreditosCollection()) {
                Tipocredito oldIdTipoCreditoOfCreditosCollectionCreditos = creditosCollectionCreditos.getIdTipoCredito();
                creditosCollectionCreditos.setIdTipoCredito(tipocredito);
                creditosCollectionCreditos = em.merge(creditosCollectionCreditos);
                if (oldIdTipoCreditoOfCreditosCollectionCreditos != null) {
                    oldIdTipoCreditoOfCreditosCollectionCreditos.getCreditosCollection().remove(creditosCollectionCreditos);
                    oldIdTipoCreditoOfCreditosCollectionCreditos = em.merge(oldIdTipoCreditoOfCreditosCollectionCreditos);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Tipocredito tipocredito) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Tipocredito persistentTipocredito = em.find(Tipocredito.class, tipocredito.getIdTipo());
            Collection<Creditos> creditosCollectionOld = persistentTipocredito.getCreditosCollection();
            Collection<Creditos> creditosCollectionNew = tipocredito.getCreditosCollection();
            List<String> illegalOrphanMessages = null;
            for (Creditos creditosCollectionOldCreditos : creditosCollectionOld) {
                if (!creditosCollectionNew.contains(creditosCollectionOldCreditos)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Creditos " + creditosCollectionOldCreditos + " since its idTipoCredito field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Creditos> attachedCreditosCollectionNew = new ArrayList<Creditos>();
            for (Creditos creditosCollectionNewCreditosToAttach : creditosCollectionNew) {
                creditosCollectionNewCreditosToAttach = em.getReference(creditosCollectionNewCreditosToAttach.getClass(), creditosCollectionNewCreditosToAttach.getIdCredito());
                attachedCreditosCollectionNew.add(creditosCollectionNewCreditosToAttach);
            }
            creditosCollectionNew = attachedCreditosCollectionNew;
            tipocredito.setCreditosCollection(creditosCollectionNew);
            tipocredito = em.merge(tipocredito);
            for (Creditos creditosCollectionNewCreditos : creditosCollectionNew) {
                if (!creditosCollectionOld.contains(creditosCollectionNewCreditos)) {
                    Tipocredito oldIdTipoCreditoOfCreditosCollectionNewCreditos = creditosCollectionNewCreditos.getIdTipoCredito();
                    creditosCollectionNewCreditos.setIdTipoCredito(tipocredito);
                    creditosCollectionNewCreditos = em.merge(creditosCollectionNewCreditos);
                    if (oldIdTipoCreditoOfCreditosCollectionNewCreditos != null && !oldIdTipoCreditoOfCreditosCollectionNewCreditos.equals(tipocredito)) {
                        oldIdTipoCreditoOfCreditosCollectionNewCreditos.getCreditosCollection().remove(creditosCollectionNewCreditos);
                        oldIdTipoCreditoOfCreditosCollectionNewCreditos = em.merge(oldIdTipoCreditoOfCreditosCollectionNewCreditos);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = tipocredito.getIdTipo();
                if (findTipocredito(id) == null) {
                    throw new NonexistentEntityException("The tipocredito with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Tipocredito tipocredito;
            try {
                tipocredito = em.getReference(Tipocredito.class, id);
                tipocredito.getIdTipo();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The tipocredito with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Creditos> creditosCollectionOrphanCheck = tipocredito.getCreditosCollection();
            for (Creditos creditosCollectionOrphanCheckCreditos : creditosCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Tipocredito (" + tipocredito + ") cannot be destroyed since the Creditos " + creditosCollectionOrphanCheckCreditos + " in its creditosCollection field has a non-nullable idTipoCredito field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(tipocredito);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Tipocredito> findTipocreditoEntities() {
        return findTipocreditoEntities(true, -1, -1);
    }

    public List<Tipocredito> findTipocreditoEntities(int maxResults, int firstResult) {
        return findTipocreditoEntities(false, maxResults, firstResult);
    }

    private List<Tipocredito> findTipocreditoEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Tipocredito.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Tipocredito findTipocredito(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Tipocredito.class, id);
        } finally {
            em.close();
        }
    }

    public int getTipocreditoCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Tipocredito> rt = cq.from(Tipocredito.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
